package com.ly.hotel.view.fragments.query;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyKeyEventCode;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.msgevent.UpdateMessageView;
import com.ly.hotel.spainterface.jxd.dialog.XFBillDialog;
import com.ly.hotel.spainterface.nm.NmXiaoFeiActivity;
import com.ly.hotel.spainterface.nm.bean.XFBillBean;
import com.ly.hotel.util.DateUtils;
import com.ly.hotel.util.LanguageUtil;
import com.ly.hotel.util.ProcessWaitingUtil;
import com.ly.hotel.util.ToastUtil;
import com.ly.hotel.view.common.BottomItemInfo;
import com.ly.hotel.view.common.HotelMassage;
import com.ly.hotel.webagent.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by SHUBEN on 2018/1/26.
 */

public class FunctionDialog extends Dialog {
    private Context context;
    private RecyclerView recyclerView;
    private MyAdapter myAdapter;
    private List<BottomItemInfo> bList = new ArrayList<>();
    private Handler handler;
    private String lang;
    private MyApplication app;
    private double totalPrice;
    private String cTime;

    public FunctionDialog(Context context, int theme) {
        super(context, theme);
        this.context = context;
        app = (MyApplication) context.getApplicationContext();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.function_dialog);
        if (LanguageUtil.isEN()) {
            lang = "en";
        } else {
            lang = "cn";
        }
        recyclerView = findViewById(R.id.fun_recycle);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:
                        parseBill(msg.obj.toString());
                        break;
                    default:
                        break;
                }
            }
        };
    }

    public void setAdapter(){
        bList.clear();
        if (MyApplication.interfaceVersion!= null){
            if(MyApplication.interfaceVersion.contains("NM")){
                bList.add(new BottomItemInfo(context.getString(R.string.xf_bill_query),"账单查询", true, MyKeyEventCode.KEYCODE_INTRO, R.drawable.btn_h_bill));
            }
        }
        bList.add(new BottomItemInfo(context.getString(R.string.naviWeatherName),"天气查询", true, MyKeyEventCode.KEYCODE_INTRO, R.drawable.btn_h_weather));


        if (myAdapter == null){
            myAdapter = new MyAdapter();
            recyclerView.setAdapter(myAdapter);
        }else{
            myAdapter.notifyDataSetChanged();
        }
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                recyclerView.requestFocus();
                recyclerView.requestFocusFromTouch();
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    //查询天气activity
    private void startWeather(){
        Intent intent = new Intent(context,WeatherActivity.class);
        context.startActivity(intent);
        dismiss();
    }

    //账单查询
    private void startBill(){
        if (!TextUtils.isEmpty(MyApplication.interfaceVersion) && !TextUtils.isEmpty(MyApplication.interfaceServerIp)
                &&!TextUtils.isEmpty(MyApplication.interfaceServerPort) && !TextUtils.isEmpty(MyApplication.myRoomNo)){
            ProcessWaitingUtil.showProcessDialog(context,"Loading...",5000);
            if(MyApplication.interfaceVersion.contains("NM")){
                final String URL = "http://" + MyApplication.interfaceServerIp + ":"
                        + MyApplication.interfaceServerPort + "/API/index.aspx";
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String request = "mid=4005&keyno=" + MyApplication.myRoomNo + "&lang=" + lang;
                        String str = new String(request.replace(" ", "%20"));
                        Log.i("httpGet", URL + "?" + str);
                        String sendRes = HttpRequest.sendGet(URL, str);
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = sendRes;
                        handler.sendMessage(msg);
                    }
                }).start();
            }
        }else {
            ToastUtil.showShortToast(context, "尚未开通", 2000);
        }
        dismiss();
    }

    private void parseBill(String text){
        ProcessWaitingUtil.closeProcessDialog();
        app.xfBillBeanList.clear();
        if (MyApplication.interfaceVersion.contains("NM")) {
            try {
                JSONObject jsObj = new JSONObject(text);
                String suc = jsObj.getString("success");
                if (suc.equals("true")) {
                    cTime = context.getString(R.string.bill_time) + "：" + jsObj.getString("create");
                    try {
                        totalPrice = Double.parseDouble(jsObj.getString("count"));
                    } catch (NumberFormatException e) {
                        totalPrice = 0;
                    }

                    String keyNo = jsObj.getString("keyno");
                    JSONArray arr = jsObj.getJSONArray("data");
                    for (int i = 0; i < arr.length(); i++) {
                        XFBillBean bb = new XFBillBean();
                        JSONObject obj = arr.getJSONObject(i);
                        String name = obj.getString("itemnane");
                        String op = obj.getDouble("price") + "";
                        String dc = obj.getDouble("discount") + "";
                        String dp = obj.getDouble("pricenew") + "";
                        String count = obj.getDouble("num") + "";
                        bb.setColumn1(keyNo);
                        bb.setColumn2(name);
                        bb.setColumn3(count);
                        bb.setColumn4(op);
                        bb.setColumn5(dc);
                        bb.setColumn6(dp);
                        app.xfBillBeanList.add(bb);
                    }

                    XFBillDialog billDialog = new XFBillDialog(context,R.style.InputDialog, app.xfBillBeanList,totalPrice);
                    billDialog.setCanceledOnTouchOutside(true);
                    billDialog.setAddMsg(null);
                    billDialog.show();
                    EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_XIAOFEI + "\t" +
                            MyApplication.interfaceVersion + "\t" + "账单查询"));
                } else {
                    String errMsg = jsObj.getString("errorMessage");
                    ToastUtil.showShortToast(context, errMsg, 2000);
                }
            } catch (JSONException e) {
                ToastUtil.showShortToast(context, e.getMessage(), 2000);
            }
        }
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{

        class ViewHolder extends RecyclerView.ViewHolder{
            View itemView;
            ImageView bottomImage;
            TextView bottomName;

            public ViewHolder(View view){
                super(view);
                itemView = view;
                bottomImage = view.findViewById(R.id.bottom_img);
                bottomName = view.findViewById(R.id.bottom_text);
            }
        }

        public MyAdapter(){}

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bottom_item,parent,false);
            final ViewHolder holder = new ViewHolder(view);
            holder.itemView.setFocusable(true);
            holder.itemView.setClickable(true);
            holder.itemView.setBackgroundResource(R.drawable.shortcut_btn_background);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = holder.getAdapterPosition();
                    String btnName = bList.get(pos).getName();
                    if(btnName.equals("天气查询")){
                        startWeather();
                    }else if(btnName.equals("账单查询")){
                        startBill();
                    }
                }
            });
            return holder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder,int position) {
            BottomItemInfo btn = bList.get(position);
            holder.bottomName.setText(btn.getShowName());
            holder.bottomImage.setImageResource(btn.getImgRes());
        }

        @Override
        public int getItemCount() {
            return bList.size();
        }
    }
}